package com.itheima.test4;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class MyThread extends Thread{

    private Socket socket;

    public MyThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //获取输入流对象
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            //读取客户端发送的文件内容并保存到本地
            //获取唯一标识符，使得文件名不唯一
            String name = UUID.randomUUID().toString().replace("-", "");
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("mysocketnet\\Serverdir\\" + name + ".jpg"));
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                //将读取到的内容保存到本地文件
                bos.write(buffer, 0, len);
            }
            //回写数据
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("文件上传成功");
            bw.newLine();
            bw.flush();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //释放资源
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
